package com.distribute.application.admin;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.distribute.application.admin.*;
import com.distribute.application.api.utils.DateUtils;
import com.distribute.framework.model.*;
import com.distribute.framework.plugin.*;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.helper.ConfigHelper;
import com.alibaba.fastjson.JSON;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.RelateClass;
import com.distribute.framework.core.lang.caption;
import com.distribute.framework.core.lang.hidden;
import com.distribute.framework.core.lang.note;
import com.distribute.framework.core.lang.primary;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.helper.ConfigHelper;

@RestController
public class AdminController {

	@RequestMapping("/")
    public void index(HttpServletResponse response) {
        try{
        	String redirect = "/admin/index.htm";
			response.setStatus(301);
			response.setHeader("Location",redirect);
			response.sendRedirect(redirect);
		} catch (Exception ex){
			ex.printStackTrace();
		}
    }
	
	@RequestMapping("/admin/config.action")
	public Protocol config() {
		try{
			Protocol protocol = Protocol.create(true);
			Long host = Utils.getLong("host");
			if(host!=null){
				if(LoginHelper.inHost(host)!=null){
					SrvUser srvUser = LoginHelper.getUser();
					if(srvUser.getId().longValue()==0l){
						srvUser.setSuHost(host.toString());
					}else{
						srvUser = SrvUser.where.suHost(host).suId(srvUser.getId()).get();
					}
					LoginHelper.setUser(srvUser);
				}else{
					protocol.setSuccess(false);
				}
			}
			Map project = Utils.add("title", Utils.config("project.title"));
			if(Utils.equals("true", Utils.config("project.debug"))){
				project.put("super", Utils.add("username", Utils.config("project.super.username")).add("password", Utils.config("project.super.password")));
				protocol.set("uid", 0);
			}
			if(LoginHelper.getUser()!=null){
				protocol.set("username", LoginHelper.getUser().getSuUsername());
				protocol.set("uid", LoginHelper.getUser().getId());
			}
			if(LoginHelper.getAdminHost()!=null){
				protocol.set("host", Utils.add("id", LoginHelper.getAdminHostId()).add("name", LoginHelper.getAdminHost().getKeyValue()));
			}
			protocol.set("lzFlashUrl", Utils.config("upload.lzFlashUrl"));
			protocol.set("uploadUrl", Utils.config("upload.uploadUrl"));
			protocol.set("project", project);
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	@RequestMapping("/admin/login.action")
	public Protocol login() { 
		try{
			Utils.setSession("super_user", null);
			HttpSession session = Utils.getHttpSession();
			String strUsername=Utils.getString("username");
			String strPassword=Utils.getString("password");		
			String strRequestSyscode=Utils.getString("syscode");
		    String strSessionSyscode = (String) session.getAttribute("syscode");
			session.removeAttribute("syscode");
			if (strRequestSyscode == null || !strRequestSyscode.toUpperCase().equals(Utils.or(strSessionSyscode,"").toUpperCase())){
				return Protocol.create(false,"对不起，验证码输入错误！");
			}
			if(strUsername==null || strUsername.trim().equals("")){
				return Protocol.create(false,"对不起，帐号输入为空！");
			}
			if(strPassword==null || strPassword.trim().equals("")){
				return Protocol.create(false,"对不起，密码输入为空！");
			}
			SrvUser user = null;
			//验证是否超级用户
			String _superUser=ConfigHelper.GetString("project.super.username");
			String _superPassword=ConfigHelper.GetString("project.super.password");
			if(strUsername.equals(_superUser) && strPassword.equals(_superPassword)){
				user=new SrvUser();//创建超级用户
				user.setSuRealName("超级用户");
				user.setSuUsername("super");
				user.setSuId((long)0);
				LoginHelper.setUser(user);
				Utils.setSession("super_user", true);
			}else{			
				SrvUser srvUser = SrvUser.where.suUsername(strUsername).get();
				if(srvUser==null){
					return Protocol.create(false,"对不起，帐号不存在！");
				}
				if(srvUser.getSuStatus()!=1){
					return Protocol.create(false,"对不起，帐号已经失效！");
				}
				
				if(!strPassword.equals(srvUser.getSuPassword()) && !Utils.md5(strPassword).equals(srvUser.getSuPassword())){
					return Protocol.create(false,"对不起，密码输入错误！");
				}
				
				SrvUser.where.suId(srvUser.getId()).set
				.suLastTime(new java.util.Date())
				.update();
				user = srvUser = SrvUser.get(srvUser.getId());
				LoginHelper.setUser(srvUser);
				//记录操作日志			
				LoggerHelper.writeLog(SrvUser.class,"LOGIN","登入系统",LoginHelper.getUserId(),"登录系统");
				
			}
			
			Utils.setCookie("/", "UID", user.getSuId()+"-"+Utils.md5(LoginHelper.PRIVATEKEY+user.getSuId()));
			LoginHelper.setUser(user);
			return Protocol.create(true, "登录成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	@RequestMapping("/admin/logout.do")
	public Protocol logout() {
		try{
			LoginHelper.setUser(null);
			Utils.setSession("session_like_host", null);
			Utils.setCookie("/", "UID", null);
			return Protocol.create(true);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	@RequestMapping("/admin/header.do")
	public Protocol header() {
		return Protocol.create(true);
	}
	
	@RequestMapping("/admin/welcome.do")
	public Protocol welcome() {
		Protocol protocol = Protocol.create(true);
		
		Calendar calendar = java.util.Calendar.getInstance();
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		protocol.set("today", Utils.date(calendar.getTime(), "yyyy年MM月dd日,星期E"));
		//售后订单数
		protocol.set("shcount", DirectOrder.where.updateTimeStart(DateUtils.getTimesmornings()).updateTimeEnd(DateUtils.getTimesnights()).status((short)5).count());
		//冲增订单数
		protocol.set("chongzcount", ProductOrder.where.paymentStatus((short)1).count());
		//已支付代理订单数
		protocol.set("dlordercount", AgentCardOrder.where.payStatus((short)2).count());
		//已支付合伙人订单数
		protocol.set("hhrcount", TbPartnerCardOrder.where.payStatus((short)2).count());
		//当前会员人数
		protocol.set("membercount", Member.where.count());
		//当前代理数
		protocol.set("dailicount", Agent.where.count());
		//今日新增代理数
		protocol.set("todydailicount", Agent.where.addTimeStart(DateUtils.getTimesmornings()).addTimeEnd(DateUtils.getTimesnights()).count());
		//当前代理数
		protocol.set("hhrcount", TbPartners.where.count());
		//今日新增合伙人数
		protocol.set("todyhhrcount", TbPartners.where.tbpPayCard((short)2).tbpAddTimeStart(DateUtils.getTimesmornings()).tbpAddTimeEnd(DateUtils.getTimesnights()).count());
		//会员提现
		protocol.set("hytxcount", MembershipRecord.where.auditType((short)1).count());
		//配送商提现
		protocol.set("tixiancount", DistributorCash.where.approvalStatus((short)1).count());
		
		
		
		
		protocol.set("counts0", DirectOrder.where.addTimeStart(calendar.getTime()).statusIn("2,3,4,5,6").count());
		protocol.set("counts1", DirectOrder.where.addTimeStart(calendar.getTime()).statusIn("2,3,4,5,6").eval("sum(total_sum)"));
		protocol.set("counts2", Member.where.addTimeStart(calendar.getTime()).count());
		protocol.set("counts3", DirectOrder.where.status(1).count());
		//今日充值成功订单
				protocol.set("counts4", ProductOrder.where.addTimeStart(new Date(DateUtils.getTimesmorning())).addTimeEnd(new Date(DateUtils.getTimesnight())).paymentStatus((short)1).status(1).count());
		protocol.set("orders", DirectOrder.where.statusNot(7).desc("id").list(5), new BeanFormat<DirectOrder>(){
			@Override
			public Map format(DirectOrder t) {
				return t.toJSON();
			}
		});
		
		protocol.set("products", ProductOrder.where.statusNot(-1).desc("id").list(5), new BeanFormat<ProductOrder>(){
			@Override
			public Map format(ProductOrder t) {
				return t.toJSON();
			}
		});
		
		calendar.add(Calendar.DATE, -12);
		List<Map> stats = DirectOrder.where.statusNot(7).addTimeStart(calendar.getTime()).stats(DirectOrder.C.totalSum, DirectOrder.C.addTime, 4);
		Map<String,String> homebars = new HashMap();
		String category = "";
		String values = "";
		for(Map item:stats){
			if(!category.equals(""))category+=",";
			if(!values.equals(""))values+=",";
			values+="'"+item.get("value")+"'";
			category+="'"+item.get("name")+"'";
		}
		homebars.put("category", category);
		homebars.put("values", values);
		homebars.put("title", "总金额");
		protocol.set("homebars", homebars);
		
		return protocol;
	}
	
	@RequestMapping("/admin/menu.do")
	public Protocol menu() {
		try{
			Protocol protocol = Protocol.create(true);
			
			Long host = Utils.getLong("host");
			if(host!=null){
				if(LoginHelper.inHost(host)!=null){
					SrvUser srvUser = LoginHelper.getUser();
					if(srvUser.getId().longValue()==0l){
						srvUser.setSuHost(host.toString());
					}else{
						srvUser = SrvUser.where.suHost(host).suId(srvUser.getId()).get();
					}
					LoginHelper.setUser(srvUser);
				}else{
					protocol.setSuccess(false);
				}
			}
			Map project = Utils.add("title", Utils.config("project.title"));
			if(LoginHelper.getUser()!=null){
				protocol.set("username", LoginHelper.getUser().getSuUsername());
			}
			if(LoginHelper.getAdminHost()!=null){
				protocol.set("host", Utils.add("id", LoginHelper.getAdminHostId()).add("name", LoginHelper.getAdminHost().getKeyValue()));
			}
			protocol.set("lzFlashUrl", Utils.config("upload.lzFlashUrl"));
			protocol.set("uploadUrl", Utils.config("upload.uploadUrl"));
			protocol.set("project", project);
			
			List<SrvProject> projects = new ArrayList();
			//获取用户支持的项目列表	
			if(LoginHelper.getUserId().longValue()==0l){
				projects = SrvProject.where.desc("sp_level").list(-1);
			}else{
				SrvUser srvUser = (SrvUser) LoginHelper.getUser();
				List<SrvLimited> list = SystemHelper.getUserLimiteds(srvUser);
				Map<Long,Integer> limits = new HashMap();
				String strIds="";
				java.util.Set<Long> mapping = new java.util.HashSet();
				for(SrvLimited o:list){
					if(mapping.contains(o.getSlProject()))continue;
					mapping.add(o.getSlProject());
					limits.put(o.getSlProject(), o.getSlLimit());					
					if(!strIds.equals(""))
						strIds+=",";
					strIds+=o.getSlProject();
					if(o.get$slProject()!=null){
						projects.add(o.get$slProject());
					}
				}
				protocol.set("limits",limits);				
			}
			java.util.Collections.sort(projects, new java.util.Comparator<SrvProject>(){
				public int compare(SrvProject o1,SrvProject o2){
					if(o1.getSpFamily().split(",").length>o2.getSpFamily().split(",").length)
						return 1;
					if(o1.getSpFamily().split(",").length==o2.getSpFamily().split(",").length && Utils.or(o1.getSpLevel(),0)<Utils.or(o2.getSpLevel(),0))
						return 1;
					return 0;
				}
			});
			protocol.set("projects", projects,new BeanFormat<SrvProject>(){
				public Map format(SrvProject t) {
					Map map = t.toJSON();
					map.put("spIcon", Utils.getIconfont(t.getSpLogo()));
					return map;
				}
			});			
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	
	@RequestMapping("/admin/hosts.do")
	public Protocol hosts(){
		try{
			List<SrvHost> list = LoginHelper.getHosts();
			List<Map> result = new java.util.ArrayList();
			for(SrvHost srvHost:list){
				Map map = new HashMap();
				map.put("key",srvHost.getId().toString());
				map.put("value", Utils.js(srvHost.getKeyValue()));
				result.add(map);
			}
			return Protocol.create().setList(result);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	
	@RequestMapping("/admin/password.do")
	public Protocol password(){
		try{
			Protocol protocol = Protocol.create(true);
			String strOld=Utils.getString("old");
			String strNew=Utils.getString("now");
			SrvUser srvUser=SrvUser.getSrvUserById(LoginHelper.getUserId());
			if(!strOld.equals(srvUser.getSuPassword()) && !Utils.md5(strOld).equals(srvUser.getSuPassword())){
				return Protocol.create(false,"旧密码输入错误");
			}
			if(!strNew.matches("((?=.*\\d)(?=.*\\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^.{8,16}$")){
				return Protocol.create(false,"密码格式错误，必须是8到16位字符，不能为纯数字或纯字母");
			}
			new SrvUser(srvUser.getId()).suPassword(Utils.md5(strNew).substring(0, 32)).update();
			return Protocol.create(true,"密码修改成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	
	
	
	@RequestMapping("/admin/vcode.action")
	public Protocol vcode() {
		Utils.getRandcode();
		return null;
	}
	
	
	@RequestMapping("/admin/struct.do")
	public String struct() {
		String className = Utils.getString("className");
		try {
			List fields = parseClass(className,Utils.getInteger("depth",0));
			return JSON.toJSONString(fields);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static List parseClass(String className,int maxDepth) throws Exception{
		return parseClass(className,new ArrayList(),"",0,maxDepth);
	}
	public static List parseClass(String calssName,List list,String parentKey,int depth,int maxDepth) throws Exception{
		if(depth>maxDepth)
			return list;
		Class<?> cls = Class.forName(calssName);
		Map<String,Boolean> fmaping = new HashMap();
		try{
			Class FClass = Class.forName(calssName+"$F");
			if(FClass!=null){
				Field[] Ffields = FClass.getFields();
				for(Field field:Ffields){
					fmaping.put(field.getName(), true);
				}
			}
		}catch(Exception ex){
			System.err.println(ex.getMessage());
		}
		Field[] fields = cls.getDeclaredFields();
		Map<String,String> names = new HashMap();
		for(Field field:fields){			
			caption caption = field.getAnnotation(caption.class);	
			note note = field.getAnnotation(note.class);
			RelateClass relateClass = field.getAnnotation(RelateClass.class);
			if(caption!=null && field.getAnnotation(hidden.class)==null){
				Map map = new HashMap();
				if(Utils.empty(parentKey))
					map.put("name",field.getName());
				else{
					map.put("name",parentKey+"."+field.getName());
					map.put("parent",parentKey.replace("[]", ""));
				}
				map.put("depth", depth);
				map.put("caption", caption.value());	
				map.put("type", field.getType().getName());
				map.put("primary", field.getAnnotation(primary.class)!=null);
				if(note!=null && note.value().indexOf("'")==-1 && note.value().indexOf("lz:")==-1 && note.value().indexOf("{")==-1)
					map.put("note", note.value());
				if(fmaping.get(field.getName()+"Start")!=null || fmaping.get(field.getName()+"Min")!=null)
					map.put("range","true");
				if(relateClass!=null)
					map.put("relate",relateClass.value().getSimpleName());
				list.add(map);
				if(relateClass!=null){ 
					//Utils.trace(caption.value(),relateClass.value().getName(),field.getType(),field.getType()==List.class);
					parseClass(relateClass.value().getName(),list,Utils.str(map.get("name"))+(field.getType()==List.class?"[]":""),depth+1,maxDepth);
				}		
			}
		}
		return list;		
	}
	
	
	static{
		new Thread(){
			public void run(){
				try {
					Thread.sleep(10000l);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Notify.on(new Notify.Listener(){
					@Override
					public <T> void execute(String message) {
						Map params = Utils.eval(message);
						String to = (String) params.get("to");
						if(to==null || to.equals("*")){
							com.distribute.framework.core.web.servlet.CometServlet.send(params);
						}else{
							for(String id:to.split(",")){
								String sid = Cache.defaultRedisSupport.getValue("USID", id);
								com.distribute.framework.core.web.servlet.CometServlet.send(params,sid);
							}
						}
					}
				}, "admin.comet");
			}
		}.start();		
	}
	
}